package com.niodata.dp.mybatis;

import com.niodata.dp.collection.WrappedMap;
import com.niodata.dp.util.JsonUtil;
import java.io.IOException;
import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

public class DefaultWrappedMapTypeHandler extends BaseTypeHandler<WrappedMap>
      implements DpMybatisTypeHandler {

  @Override
  public JdbcType getJdbcType() {
    return JdbcType.LONGVARCHAR;
  }

  @Override
  public Class getTypeHandlerClass() {
    return DefaultWrappedMapTypeHandler.class;
  }

  @Override
  public Class getJavaClass() {
    return WrappedMap.class;
  }

  @Override
  public void setNonNullParameter(
        PreparedStatement ps, int i, WrappedMap parameter, JdbcType jdbcType) throws SQLException {
    try {
      ps.setString(i, JsonUtil.toJson(parameter));
    } catch (IOException ioe) {
      ioe.printStackTrace();
    }
  }

  @Override
  public WrappedMap getNullableResult(ResultSet rs, String columnName) throws SQLException {
    try {
      String str = rs.getString(columnName);
      if (str != null) {
        return JsonUtil.fromJson(WrappedMap.class, str);
      }
      return new WrappedMap();
    } catch (IOException e) {
      e.printStackTrace();
    }
    return null;
  }

  @Override
  public WrappedMap getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
    try {
      return JsonUtil.fromJson(WrappedMap.class, rs.getString(columnIndex));
    } catch (IOException e) {
      e.printStackTrace();
    }
    return null;
  }

  @Override
  public WrappedMap getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
    return null;
  }
}
